//
//  Test6ViewController.m
//  JKNSURLSession
//
//  Created by 王冲 on 2019/1/22.
//  Copyright © 2019年 JK科技有限公司. All rights reserved.
//

#import "Test6ViewController.h"

#import "JKProgressBtn.h"
@interface Test6ViewController ()<NSURLSessionDownloadDelegate>

// 全局的网络会话，管理所有的网络任务
@property(nonatomic,strong) NSURLSession *session;

// 进度的View
@property(nonatomic,strong) JKProgressBtn *progressView;

/**
  设置一个全局的下载任务
 */
@property(nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

/**
 保存断开时的data
 */
@property(nonatomic,strong) NSData *resumeData;

@end

@implementation Test6ViewController

-(JKProgressBtn *)progressView{
    
    if (!_progressView) {
        
        _progressView = [[JKProgressBtn alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2-50, [UIScreen mainScreen].bounds.size.height/2-50, 100, 100)];
        _progressView.backgroundColor = [UIColor yellowColor];
    }
    
    return _progressView;
}

-(NSURLSession *)session{
    
    // NSURLSession 默认是在子线程开启任务的
    if (!_session) {
        
        /**
         全局网络环境的一个配置
         比如：身份验证，浏览器类型以及缓存，超时，这些都会被记录在
         */
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 添加进度View
    [self.view addSubview:self.progressView];
    
    UIButton *buttton1 = [[UIButton alloc]initWithFrame:CGRectMake(20, 150, 100, 40)];
    [buttton1 setTitle:@"开始下载" forState:UIControlStateNormal];
    [buttton1 setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [buttton1 setBackgroundColor:[UIColor yellowColor]];
    [buttton1 addTarget:self action:@selector(startLoadTask) forControlEvents:UIControlEventTouchUpInside];
    buttton1.titleLabel.font = [UIFont systemFontOfSize:18.f];
    [self.view addSubview:buttton1];
    
    UIButton *buttton2 = [[UIButton alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(buttton1.frame)+20, 100, 40)];
    [buttton2 setTitle:@"暂停下载" forState:UIControlStateNormal];
    [buttton2 setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [buttton2 setBackgroundColor:[UIColor yellowColor]];
    [buttton2 addTarget:self action:@selector(pauseLoadTask) forControlEvents:UIControlEventTouchUpInside];
    buttton2.titleLabel.font = [UIFont systemFontOfSize:18.f];
    [self.view addSubview:buttton2];
    
    UIButton *buttton3 = [[UIButton alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(buttton2.frame)+20, 100, 40)];
    [buttton3 setTitle:@"继续下载" forState:UIControlStateNormal];
    [buttton3 setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [buttton3 setBackgroundColor:[UIColor yellowColor]];
    [buttton3 addTarget:self action:@selector(resumeLoadTask) forControlEvents:UIControlEventTouchUpInside];
    buttton3.titleLabel.font = [UIFont systemFontOfSize:18.f];
    [self.view addSubview:buttton3];
    
}

/**
 1、下载完成的方法
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    JKLog(@"下载完成");
    [self.session finishTasksAndInvalidate];
    self.session = nil;
}

/**
 2、下载续传数据的方法
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
    
}

/**
 3、下载进度的方法
 
 @param session 网络会话
 @param downloadTask 调用代理方式的下载任务
 @param bytesWritten 本次下载的字节数
 @param totalBytesWritten 已经下载的字节数
 @param totalBytesExpectedToWrite 期望下载的字节数 -- 文件的总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    float progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
    JKLog(@"进度=%f",progress);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.progressView.progress = progress;
    });
}

#pragma mark 开始下载
-(void)startLoadTask{
    
    NSLog(@"开始下载");
    // 1.创建url:http://localhost
    NSURL *url = [NSURL URLWithString:@"http://localhost/2ittt-zm.mp4"];
    self.downloadTask = [self.session downloadTaskWithURL:url];
    // 执行下载
    [self.downloadTask resume];
    
}

#pragma mark 暂停下载
-(void)pauseLoadTask{
    
    NSLog(@"暂停下载");
    
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
        NSLog(@"数据的长度是:%tu",resumeData.length);
        
        self.resumeData = resumeData;
        
        //释放任务
        self.downloadTask = nil;
    }];
}

#pragma mark 继续下载
-(void)resumeLoadTask{
    
    NSLog(@"继续下载");
    
    if (self.resumeData == nil) return;
    
    self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
    self.resumeData = nil;
    [self.downloadTask resume];
}

-(void)dealloc{
    
    NSLog(@"销毁下载的控制器");
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.session invalidateAndCancel];
    self.session = nil;
}

@end
